import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  //一级路由
  { path: '/login', component: () => import('@/views/Login') },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/views/Home'),
    children: [
      { path: 'dashboard', component: () => import('@/views/Home/Dashboard') },
      { path: 'user', component: () => import('@/views/Home/User') },
      { path: 'category', component: () => import('@/views/Home/Category') },
      { path: 'post', component: () => import('@/views/Home/Post') },
      { path: 'update', component: () => import('@/views/Home/updateBlogs') },
    ],
  },
  { path: '*', component: () => import('@/views/NotFound') },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

// 设置导航守卫
router.beforeEach((to, from, next) => {
  //to:需要访问的路径
  //from: 从哪里来
  //next:放行

  //定义一个登入的状态
  let isLogin = localStorage.getItem('isLogin') === '1' ? true : false;

  if (isLogin) {
    //登入状态
    if (to.path == 'login') {
      next('/dashboard');
    } else {
      next();
    }
  } else {
    if (to.path != '/login') {
      alert('请先登入');
      next('/login');
    } else {
      next();
    }
  }
});
export default router;
